#define _CRT_SECURE_NO_WARNINGS
#include "List.h"


LTNode* CreateNode(LTDataType x)
{
	LTNode* listnode = (LTNode*)malloc(sizeof(LTNode));
	if (listnode == NULL)
	{
		perror("malloc fail");
		return NULL;
	}

	listnode->next = NULL;
	listnode->prev = NULL;
	listnode->data = x;

	return listnode;
}


LTNode* LTInit()
{
	LTNode* newnode = CreateNode(-1);
	newnode->next = newnode;
	newnode->prev = newnode;

	return newnode;
}


void LTPrint(LTNode* phead)
{
	LTNode* cur = phead->next;
	printf("sentinel<==>");
	while (cur != phead)
	{
		printf("%d<==>", cur->data);

		cur = cur->next;
	}
	printf("\n");
}


void LTPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);

	/*LTNode* newnode = CreateNode(x);
	LTNode* next = phead->next;

	phead->next = newnode;
	newnode->prev = phead;
	newnode->next = next;
	next->prev = newnode;*/
	LTInsert(phead->next, x);
}


void LTPushBack(LTNode* phead, LTDataType x)
{
	assert(phead);

	/*LTNode* newnode = CreateNode(x);
	LTNode* tail = phead->prev;

	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;*/
	LTInsert(phead, x);
}


bool LTEmpty(LTNode* phead)
{
	assert(phead);

	return phead->next == phead;
}


void LTPopFront(LTNode* phead)
{
	assert(phead);
	assert(!LTEmpty(phead));

	/*LTNode* first = phead->next;
	LTNode* second = first->next;

	phead->next = second;
	second->prev = phead;
	free(first);*/
	LTErase(phead->next);
}


void LTPopBack(LTNode* phead)
{
	assert(phead);
	assert(!LTEmpty(phead));

	/*LTNode* tail = phead->prev;
	LTNode* tailprev = tail->prev;

	phead->prev = tailprev;
	tailprev->next = phead;
	free(tail);*/
	LTErase(phead->prev);
}


LTNode* LTFind(LTNode* phead, LTDataType x)
{
	assert(phead);

	LTNode* cur = phead->next;
	while (cur->next != phead)
	{
		if (cur->data == x)
		{
			return cur;
		}

		cur = cur->next;
	}
	return NULL;
}


void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos);

	LTNode* newnode = CreateNode(x);
	LTNode* posPrev = pos->prev;

	newnode->prev = posPrev;
	newnode->next = pos;
	posPrev->next = newnode;
	pos->prev = newnode;
}


void LTErase(LTNode* pos)
{
	assert(pos);

	LTNode* posPrev = pos->prev;
	LTNode* posNext = pos->next;

	posPrev->next = posNext;
	posNext->prev = posPrev;
	free(pos);
}


void LTDestroy(LTNode* phead)
{
	assert(phead);

	LTNode* cur = phead->next;
	while (cur != phead)
	{
		LTNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(phead);
}

